package com.example.musicplayer.provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.musicplayer.entity.MusicList;
import com.example.musicplayer.util.DbHelper;

public class MusicListProvider extends ContentProvider {

    private DbHelper mDbHelper;
    private SQLiteDatabase sqLiteDatabase;
    private static final String DB_NAME = "music";
    private static final String DB_TABLE = "musiclist";
    private static final UriMatcher URI_MATCHER;
    private static final String AUTHORITIES = "com.example.musicplayer.provider.musiclistprovider";
    private static final String PATH_SINGLE = "musiclist/#";
    private static final String PATH_MULTIPLE = "musiclist";
    private static final String CONTENT_URI_STRING = "content://" + AUTHORITIES + "/" + PATH_MULTIPLE;
    public static final Uri CONTENT_URI = Uri.parse(CONTENT_URI_STRING);
    private static final int DB_VERSION = 1;
    private static final int SINGLE_CODE = 1;
    private static final int MULTIPLE_CODE = 2;
    private static final String MIME_DIR_PREFIX = "vnd.android.cursor.dir";
    private static final String MIMI_ITEM_PREFIX = "vnd.android.cursor.item";
    private static final String MINE_ITEM = "vnd.music.musiclist";
    private static final String MINE_TYPE_SINGLE = MIMI_ITEM_PREFIX + "/" + MINE_ITEM;
    private static final String MINE_TYPE_MULTIPLE = MIME_DIR_PREFIX + "/" + MINE_ITEM;

    public static final String SQL = "CREATE TABLE " + DB_TABLE +
            "(" + MusicList.MUSIC_LIST_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            MusicList.MUSIC_LIST_NAME + " TEXT NOT NULL)";

    static {
        URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
        URI_MATCHER.addURI(AUTHORITIES, PATH_SINGLE, SINGLE_CODE);
        URI_MATCHER.addURI(AUTHORITIES, PATH_MULTIPLE, MULTIPLE_CODE);
    }

    @Override
    public boolean onCreate() {
        mDbHelper = new DbHelper(getContext(), DB_NAME, null, DB_VERSION, DB_TABLE);
        sqLiteDatabase = mDbHelper.getWritableDatabase();
        return sqLiteDatabase != null;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
        queryBuilder.setTables(DB_TABLE);
        if (URI_MATCHER.match(uri) == SINGLE_CODE) {
            queryBuilder.appendWhere(MusicList.MUSIC_LIST_ID + "=" + uri.getPathSegments().get(1));
        }
        Cursor cursor = queryBuilder.query(sqLiteDatabase, projection, selection, selectionArgs, null, null, sortOrder);
        if (cursor == null) {
            return null;
        }
        if (getContext() != null) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return cursor;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        switch (URI_MATCHER.match(uri)) {
            case MULTIPLE_CODE:
                return MINE_TYPE_MULTIPLE;
            case SINGLE_CODE:
                return MINE_TYPE_SINGLE;
            default:
                throw new IllegalArgumentException("Unknown Uri" + uri);
        }
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        long id = sqLiteDatabase.insert(DB_TABLE, null, values);
        if (id > 0) {
            Uri newUri = ContentUris.withAppendedId(CONTENT_URI, id);
            if (getContext() != null) {
                getContext().getContentResolver().notifyChange(newUri, null);
            }
            return newUri;
        }
        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        int count;
        switch (URI_MATCHER.match(uri)) {
            case MULTIPLE_CODE:
                count = sqLiteDatabase.delete(DB_TABLE, selection, selectionArgs);
                break;
            case SINGLE_CODE:
                String segment = uri.getPathSegments().get(1);
                count = sqLiteDatabase.delete(DB_TABLE, MusicList.MUSIC_LIST_ID + "=" + segment, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Wrong URI" + uri);
        }
        if (getContext() != null) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return count;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        int count; // 数据库中被改变的行数
        switch (URI_MATCHER.match(uri)) {
            case MULTIPLE_CODE:
                count = sqLiteDatabase.update(DB_TABLE, values, selection, selectionArgs);
                break;
            case SINGLE_CODE:
                String segment = uri.getPathSegments().get(1);
                count = sqLiteDatabase.update(DB_TABLE, values, MusicList.MUSIC_LIST_ID + "=" + segment, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI" + uri);
        }
        if (getContext() != null) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return count;
    }
}
